package manager

import ext.log
import org.json.JSONObject

object VersionManager : Runnable {
    private var clientPath = ""

    override fun run() {

    }

    fun checkUpdate() {
        if (clientPath.isEmpty() || AppManager.isBusy) {
            return
        }
        AppManager.installApk(clientPath)
        clientPath = ""
    }

    fun updateWithServer(json: JSONObject) {
        val curl = json.optString("clientfileUrl")
        if (curl.isEmpty()) {
            val clientUrl = json.optString("lowerfileUrl")
            if (clientUrl.isEmpty()) {
                return
            }
            TaskManager.DelayHandler.post(OTAManager.DownTask(clientUrl))
            return
        }
        TaskManager.DelayHandler.post(ClientVersionUpdateTask(curl))
    }

    private class ClientVersionUpdateTask(val url: String) : Runnable {
        override fun run() {
            try {
                log("开始下载客户端更新文件", "客户端升级")
                val file = HttpRequestManager.downLoadFile("client.apk", url)
                log("客户端下载成功", "客户端升级")
                clientPath = file.path
                VersionManager.checkUpdate()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}